package cn.schoolwow.quickdao.module.database.dml.instance.flow.common;

import cn.schoolwow.quickdao.annotation.IdStrategy;
import cn.schoolwow.quickdao.domain.entity.Entity;
import cn.schoolwow.quickdao.module.database.dml.common.domain.ManipulationOption;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.reflection.QueryReflection;

import java.lang.reflect.Field;

public class SetGenerateKeysFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        ManipulationOption manipulationOption = flowContext.checkInstanceData(ManipulationOption.class);
        Entity entity = (Entity) flowContext.checkData("entity");
        Object instance = flowContext.checkData("instance");

        //设置自增id
        if (manipulationOption.returnGeneratedKeys && null != entity.id && entity.id.strategy.equals(IdStrategy.AutoIncrement)) {
            String generatedKeys = (String) flowContext.checkData("generateKeys");
            setGeneratedKeysValue(instance, entity, generatedKeys);
        }
    }

    @Override
    public String name() {
        return "设置自增id";
    }

    private void setGeneratedKeysValue(Object instance, Entity entity, String generatedKeys) throws IllegalAccessException {
        Field idField = QueryReflection.newQuery(instance.getClass())
                .execute()
                .getField(entity.id.name);
        switch (idField.getType().getName()) {
            case "int": {
                idField.setInt(instance, Integer.parseInt(generatedKeys));
            }
            break;
            case "java.lang.Integer": {
                idField.set(instance, Integer.valueOf(generatedKeys));
            }
            break;
            case "long": {
                idField.setLong(instance, Long.parseLong(generatedKeys));
            }
            break;
            case "java.lang.Long": {
                idField.set(instance, Long.valueOf(generatedKeys));
            }
            break;
            case "java.lang.String": {
                idField.set(instance, generatedKeys);
            }
            break;
            default: {
                throw new IllegalArgumentException("当前仅支持int,long,String类型的自增主键!自增字段名称:" + idField.getName() + ",类型:" + idField.getType().getName() + "!");
            }
        }
    }
}
